package com.avic.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.avic.gateway.common.constant.GatewayConstant;
import com.avic.gateway.common.util.Base64Util;
import com.avic.gateway.model.LoginResponse;
import com.avic.gateway.model.ServiceLoginRes;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.concurrent.TimeUnit;

/**
 * 登入创建Token过滤器
 *
 * @author: huangsheng
 * @date: 2018/8/24
 */
@Slf4j
public class LoginCreateTokenPostFilter extends AbstractZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 9;
    }

    @Override
    public boolean shouldFilter() {
        return shouldFilter(LoginCreateTokenPostFilter.class.getSimpleName());
    }

    public static final String TOKEN_PRE = "date";

    @Override
    public Object run() {

        RequestContext requestContext = RequestContext.getCurrentContext();
        String loginResult = requestContext.getResponseBody();
        log.info("登入结果 {}", loginResult);

        // 校验登入是否成功，成功则生产Token返回
        if (StringUtils.isNotBlank(loginResult) && StringUtils.equals(
                requestContext.getRequest().getMethod(), RequestMethod.POST.name())) {
            ServiceLoginRes loginRes;
            try {
                loginRes = objectMapper.readValue(loginResult, ServiceLoginRes.class);
            } catch (Exception e) {
                log.info("objectMapper readValue LoginRes error：message {}", e.getMessage());
                loginRes = JSON.parseObject(loginResult, new TypeReference<ServiceLoginRes>() {
                });
            }

            if (loginRes.isSuccess()) {
                try {

                    String gateway_auth = Base64Util.encodeToString(loginRes.getUserId() + TOKEN_PRE + System.currentTimeMillis());
                    log.info("生成Token {} ", gateway_auth);

                    // 设置过期时间为30分钟
                    redisTemplate.opsForValue().set(GatewayConstant.REDIS_MANAGEMENT_TOKEN_SPACE + loginRes.getUserId(), gateway_auth, 30, TimeUnit.MINUTES);
                    LoginResponse loginResponse = new LoginResponse();
                    loginResponse.setManagementToken(gateway_auth);
                    loginResponse.setSuccess(true);
                    // 设置新的reponse
                    requestContext.setResponseBody(objectMapper.writeValueAsString(loginResponse));
                } catch (Exception e) {
                    log.info("create auth error {}", e.getMessage());
                    throw new RuntimeException();
                }
            }
        }
        return null;
    }

}
